//
//  PGOAuthViewController.swift
//  PGWeibo
//
//  Created by Apple on 15/11/5.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import SVProgressHUD
class PGOAuthViewController: UIViewController, UIWebViewDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
        navigationItem.title = "登录到新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
    }
    /// webView
    private lazy var webView: UIWebView = {
        var view = UIWebView()
        let tools = PGNetworkTools.sharedTools.oauthUrl
        view.loadRequest(NSURLRequest(URL: tools))
        return view
    }()
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    @objc private func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func autoFill() {
        let js = "document.getElementById('userId').value = '15931427332';" +
        "document.getElementById('passwd').value = 'tuotuo520';"
        
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
}
// MARK: - webView代理
extension PGOAuthViewController {
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //守卫 是否有主机地址www.baidu.com
        guard let url = request.URL where url.host == "www.baidu.com" else {
            return true
        }
        //守卫 是否返回 code=授权码
        guard let query = url.query where query.hasPrefix("code=") else {
            close()
            return false
        }
        //截取 授权码
        let code = query.substringFromIndex("code=".endIndex)
        
        PGUserAccountViewModel.sharedUerAccountViewModel.loadAccessToken(code) { (isSuccessed) -> () in
            if isSuccessed {
                print("授权成功")
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    
                    NSNotificationCenter.defaultCenter().postNotificationName(PGSwitchRootControllerNotification, object: "welcome")
                    SVProgressHUD.dismiss()
                })
            }else{
                SVProgressHUD.showInfoWithStatus("不给力")
                print("授权出错")
                self.close()
            }
        }
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}

